package com.spider.spiderflowable.common;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * 捕获OAuth2Exception 返回统一格式
 *
 * @author xiong.bo
 * @version 1.0
 * @date 2025/3/22 9:56 下午
 */

@Component
public class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {

  @Override
  public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
    ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);

    // 自定义错误响应
    OAuth2Exception oAuth2Exception = responseEntity.getBody();
    if (oAuth2Exception != null) {

      // 直接返回自定义响应
      Result result = Result.error(
          oAuth2Exception.getHttpErrorCode(),
          oAuth2Exception.getMessage(),
          oAuth2Exception.getOAuth2ErrorCode()
      );
      return new ResponseEntity(result, HttpStatus.valueOf(oAuth2Exception.getHttpErrorCode()));
    }
    throw e;
  }
}
